package com.lutzyt.delivery.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lutzyt.delivery.bean.Customer;
import com.lutzyt.delivery.bean.Horseman;
import com.lutzyt.delivery.bean.HorsemanAccountFlow;
import com.lutzyt.delivery.mapper.HorsemanDAO;
import com.lutzyt.delivery.service.HorsemanAccountFlowService;
import com.lutzyt.delivery.service.HorsemanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.UUID;

/**
 * @author zyt
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class HorsemanServiceImpl extends ActionServiceImpl<HorsemanDAO, Horseman> implements HorsemanService {

  private HorsemanDAO horsemanDAO;
  private HorsemanAccountFlowService flowService;

  @Transactional(readOnly = true)
  @Override
  public Horseman findById(Integer id) {
    return horsemanDAO.selectById(id);
  }

  @Transactional(readOnly = true)
  @Override
  public IPage<Horseman> findByPage(int pageNum, int pageSize) {
    return horsemanDAO.selectPage(new Page<>(pageNum, pageSize), null);
  }

  @Override
  public void insert(Horseman horseman) {
    horsemanDAO.insert(horseman);
  }

  @Override
  public void update(Horseman horseman) {
    horsemanDAO.updateById(horseman);
  }

  @Override
  public void deleteById(Integer id) {
    horsemanDAO.deleteById(id);
  }

  @Override
  public Integer register(String horsemanOpenId) {
    Horseman horseman = new Horseman();
    horseman.setHeadPortrait("#");
    horseman.setUsername("~");
    horseman.setBalance(BigDecimal.ZERO);
    horseman.setCode(UUID.randomUUID().toString());
    horseman.setPassword("123456");
    horseman.setName("~");
    horseman.setPhone("~");
    horseman.setWxOpenid(horsemanOpenId);
    this.save(horseman);
    return horseman.getId();
  }

  @Override
  public void withdraw(String id) {
    final Horseman horseman = this.getById(id);
    final BigDecimal balance = horseman.getBalance();
    horseman.setBalance(BigDecimal.ZERO);
    this.updateById(horseman);
    HorsemanAccountFlow flow = new HorsemanAccountFlow();
    flow.setAmount(balance);
    flow.setHorsemanId(horseman.getId());
    flow.setAction("SUB");
    flowService.save(flow);
  }

  @Autowired
  public void setFlowService(HorsemanAccountFlowService flowService) {
    this.flowService = flowService;
  }

  @Autowired
  public void setHorsemanDAO(HorsemanDAO horsemanDAO) {
    this.horsemanDAO = horsemanDAO;
  }
}